﻿using System.Collections.Generic;
using System.IO;
using System.Text;

using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;

namespace Livres
{
    [DataContract]
    public class Livre
    {
        #region Attributs
        private string _nom;
        private string _auteur;
        private Dictionary<int, Chapitre> _chapitres;
        private string _fileName;
        #endregion

        #region Constructeur
        public Livre()
        {
            _chapitres = new Dictionary<int, Chapitre>();
        }
        #endregion

        #region Proprietes
        [DataMember(Order = 0)]
        public string Nom
        {
            get { return _nom; }
            set { _nom = value; }
        }

        [DataMember(Order = 1)]
        public string Auteur
        {
            get { return _auteur; }
            set { _auteur = value; }
        }

        [XmlIgnore]
        [IgnoreDataMember]
        public int NombreChapitre
        {
            get { return Chapitres.Count; }
        }

        [DataMember(Order = 2)]
        public Dictionary<int, Chapitre> Chapitres
        {
            get { return _chapitres; }
            set
            {
                _chapitres = value;
            }
        }

        [XmlIgnore]
        [IgnoreDataMember]
        public Chapitre this[int i]
        {
            get
            {
                foreach (var item in Chapitres)
                {
                    if (item.Key == i)
                        return item.Value;
                }
                return null;
            }
        }

        [XmlIgnore]
        [IgnoreDataMember]
        public string FileName
        {
            get { return _fileName; }
            set { _fileName = value; }
        }
        #endregion

        #region Methodes
        public void Save(Stream stream)
        {

            DataContractSerializer dcs = new DataContractSerializer(typeof(Livre), null, int.MaxValue, false, true, null);
            using (XmlDictionaryWriter xdw = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8))
            {
                dcs.WriteObject(xdw, this);
            }
        }

        public void Open(Stream stream)
        {
            DataContractSerializer dcs = new DataContractSerializer(typeof(Livre), null, int.MaxValue, false, true, null);
            using (XmlDictionaryReader xdr = XmlDictionaryReader.CreateTextReader(stream, Encoding.UTF8, new XmlDictionaryReaderQuotas() { MaxDepth = int.MaxValue }, null))
            {
                Livre l = (Livre)dcs.ReadObject(xdr);
                this.Auteur = l.Auteur;
                this.Chapitres = l.Chapitres;
                this.Nom = l.Nom;
            }
        }
        #endregion
    }
}
